#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""报告

报告

Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""


from wingman import db_query
from wingman import send
from wingman import logger
from wingman.common.error import ErrorCode
from wingman import is_holiday, is_first_month, is_first_monday


class CustomReport:

    # TODO:节日独判断有问题，周未也会发送日报 (负责人: Z, 截止日期: 2023-12-31)
    def generate_report(self):
        """显式地生成报告"""
        if is_holiday:
            return None
        elif is_first_month:
            logger.debug(ErrorCode.DEBUG.value, is_first_month, __name__)
            return self.get_month(), self.get_yesterday()
        elif is_first_monday:
            logger.debug(ErrorCode.DEBUG.value, is_first_month, __name__)
            return self.get_monday(), self.get_yesterday()
        else:
            return self.get_yesterday()

    def _get_daily_count(self, table: str,) -> int:
        """获取每日数据"""
        query = f"""
            SELECT COUNT(*)
            FROM {table}
            WHERE DATE(create_time) = CURDATE();
        """
        try:
            return db_query(query)
        except Exception as e:
            logger.debug(ErrorCode.DEBUG.value, str(e), __name__)
            return 0

    def _get_weekly_count(self, table: str) -> int:
        """获取每周数据"""
        query = f"""
            SELECT COUNT(*)
            FROM {table}
            WHERE create_time >= DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) + 7 DAY) 
              AND create_time < DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY);
        """
        try:
            return db_query(query)
        except Exception as e:
            logger.error(f"查询{table}失败: {str(e)}")
            return 0

    def _get_yesterday_count(self, table: str) -> int:
        """获取昨日数据"""
        query = f"""
            SELECT COUNT(*)
            FROM {table}
            WHERE DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY);
        """
        try:
            return db_query(query)
        except Exception as e:
            logger.error(f"查询{table}失败: {str(e)}")
            return 0

    def _get_last_month_count(self, table: str) -> int:
        """获取上月数据"""
        query = f"""
            SELECT COUNT(*)
            FROM {table}
            WHERE create_time >= DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 1 MONTH), '%Y-%m-01')
              AND create_time < DATE_FORMAT(CURDATE(), '%Y-%m-01');
        """
        try:
            return db_query(query)
        except Exception as e:
            logger.error(f"查询{table}失败: {str(e)}")
            return 0

    def _generate_report_section(self, table: str) -> dict:
        """生成报告段落，返回字典格式"""
        count = self._get_daily_count(table)
        return count

    def _generate_yesterday_section(self, table: str) -> dict:
        """生成昨日报告段落，返回字典格式"""
        count = self._get_yesterday_count(table)
        return count

    def _generate_weekly_section(self, table: str) -> dict:
        """生成周报段落，返回字典格式"""
        count = self._get_weekly_count(table)
        return count

    def _generate_monthly_section(self, table: str) -> dict:
        """生成月报段落，返回字典格式"""
        count = self._get_last_month_count(table)
        return count

    def _send_report(self, report_type: str, sections: dict) -> dict:
        """发送报告通用方法"""
        result = {
            "title": "report",
            "customize_env": "debug",
        }
        result.update(sections)
        send(result, "report")
        return result

    def get_everyday(self) -> dict:
        """发送当天日报"""
        sections = {
            "inspection": self._generate_report_section("inspection_exception"),
            "prometheus": self._generate_report_section("prometheus_alerts"),
            "syslog": self._generate_report_section("logger_syslog"),
            "nginx_error": self._generate_report_section("logger_nginx_error"),
            "nginx_status": self._generate_report_section("logger_nginx"),
            "mysql_slow": self._generate_report_section("logger_mysql_slow"),
            "mysql_error": self._generate_report_section("logger_mysql_error"),
            "java_info": self._generate_report_section("logger_java_info"),
            "java_error": self._generate_report_section("logger_java_error")
        }
        return self._send_report("daily_report", sections)

    def get_yesterday(self) -> dict:
        """发送昨日报告"""
        sections = {
            "inspection": self._generate_yesterday_section("inspection_exception"),
            "prometheus": self._generate_yesterday_section("prometheus_alerts"),
            "syslog": self._generate_yesterday_section("logger_syslog"),
            "nginx_error": self._generate_yesterday_section("logger_nginx_error"),
            "nginx_status": self._generate_yesterday_section("logger_nginx"),
            "mysql_slow": self._generate_yesterday_section("logger_mysql_slow"),
            "mysql_error": self._generate_yesterday_section("logger_mysql_error"),
            "java_info": self._generate_yesterday_section("logger_java_info"),
            "java_error": self._generate_yesterday_section("logger_java_error")
        }
        return self._send_report("yesterday_report", sections)

    def get_monday(self) -> dict:
        """发送周报"""
        sections = {
            "inspection": self._generate_weekly_section("inspection_exception"),
            "prometheus": self._generate_weekly_section("prometheus_alerts"),
            "syslog": self._generate_weekly_section("logger_syslog"),
            "nginx_error": self._generate_weekly_section("logger_nginx_error"),
            "nginx_status": self._generate_weekly_section("logger_nginx"),
            "mysql_slow": self._generate_weekly_section("logger_mysql_slow"),
            "mysql_error": self._generate_weekly_section("logger_mysql_error"),
            "java_info": self._generate_weekly_section("logger_java_info"),
            "java_error": self._generate_weekly_section("logger_java_error")
        }
        return self._send_report("weekly_report", sections)

    def get_month(self) -> dict:
        """发送月报"""
        sections = {
            "inspection": self._generate_monthly_section("inspection_exception"),
            "prometheus": self._generate_monthly_section("prometheus_alerts"),
            "syslog": self._generate_monthly_section("logger_syslog"),
            "nginx_error": self._generate_monthly_section("logger_nginx_error"),
            "nginx_status": self._generate_monthly_section("logger_nginx"),
            "mysql_slow": self._generate_monthly_section("logger_mysql_slow"),
            "mysql_error": self._generate_monthly_section("logger_mysql_error"),
            "java_info": self._generate_monthly_section("logger_java_info"),
            "java_error": self._generate_monthly_section("logger_java_error")
        }
        return self._send_report("monthly_report", sections)


if __name__ == "__main__":
    report = CustomReport()
    print(report.generate_report())
    # print(report.get_yesterday())
    # print(report.get_everyday())
    # print(report.get_monday())
    # print(report.get_month())
